package pers.qianyu.month_202012.date_20201212;

import org.junit.*;

import java.util.*;

/**
 * 402. 移掉K位数字
 * https://leetcode-cn.com/problems/remove-k-digits/
 *
 * @author mizzle rain
 * @date 2020-12-12 19:46
 */
public class RemoveKdigits {
    public String removeKdigits(String num, int k) {
        Stack<Character> st = new Stack<>();
        for (int i = 0; i < num.length(); i++) {
            while (!st.isEmpty() && st.peek() > num.charAt(i) && k > 0) {
                st.pop();
                k--;
            }
            st.push(num.charAt(i));
        }
        // 如果k没有到0的话，就排除后面的 k 个字符
        while (k-- > 0) {
            st.pop();
        }
        StringBuilder builder = new StringBuilder();
        for (Character ch : st) {
            // 忽略字符串前面的 0
            if (builder.length() == 0 && ch.equals('0')) {
                continue;
            }
            builder.append(ch);
        }
        return builder.toString().equals("") ? "0" : builder.toString();
    }

    @Test
    public void test1() {
        String result = new RemoveKdigits().removeKdigits("1432219", 3);
        System.out.println("result = " + result);
    }

    @Test
    public void test2() {
        String result = new RemoveKdigits().removeKdigits("10", 2);
        System.out.println("result = " + result);
    }

    @Test
    public void test3() {
        String result = new RemoveKdigits().removeKdigits("1432219", 3);
        System.out.println("result = " + result);
    }

    @Test
    public void test4() {
        String result = new RemoveKdigits().removeKdigits("10200", 1);
        System.out.println("result = " + result);
    }

    @Test
    public void test5() {
        String result = new RemoveKdigits().removeKdigits("9", 1);
        System.out.println("result = " + result);
    }
}
